home *** CD-ROM | disk | FTP | other *** search
- Path: hursley.ibm.com!news
- From: Max Waterman <dwater@wight.hursley.ibm.com>
- Newsgroups: comp.lang.c
- Subject: Re: Is This Bad Coding Practice?
- Date: Tue, 02 Apr 1996 14:32:06 +0100
- Organization: IBM UK Laboratories Ltd.
- Message-ID: <31612C56.4487@wight.hursley.ibm.com>
- References: <4jgnt2$9d1@loki.tor.hookup.net> <828135115snz@genesis.demon.co.uk>
- NNTP-Posting-Host: wight.hursley.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; AIX 2)
-
- In article <4jgnt2$9d1@loki.tor.hookup.net>
- Rajendra_Singh@msn.com "Rajendra Singh" writes:
-
- >int main(int argc, char *argv[])
- > {
- > char string[128];
- > char *func1(void);
- >
- > strcpy(string, func1());
- > return 0;
- > }
- >
- >char *func1(void)
- > {
- > char test[100];
- >
- > sprintf(test, "Test: %d", 1);
- > return test;
- > }
- >
- >... since I am using the value returned from func1() immediately (in
- >main()), is this reliable?
-
- As others have pointed out; no, this is bad code. It may well work under
- debug mode, but as soon as you turn any significant optimisations on,
- code relying on this behaviour will fail.
-
- Alternatives I can think of would be to :
-
- 1) declare test[100] as static;
-
- 2) declare automatic test in main() and pass address to func1;
-
- 3) malloc()/free() some memory in main() for func1() to use - pass
- address of memory to func1();
-
- Option 2) in the case above would be my favoured choice.
-
- It also strikes me as not good practice to call a function in the call
- to another. In most cases, it is best to call func1() first, then call
- strcpy()/whatever.
-
- I guess the #include's where ommited for bevity?
-
- Also, I don't think there is a need to declare the args to main() if
- they're not being used. Suggest int main( void ) would be better.
- Anyone?
-
- Max.
- --
- ___ mailto:max@lton.u-net.com
- / / / _ / / _ __ __ _ __ _
- / / / /_/ |/ / / / /_/ / /_ /_/ / / / /_/ /| /
- / / / / / /| /_/_/ / / / /_ / | / / / / / / |/
-